"""
Browser management module for HeyGen video generator.
Handles browser initialization, configuration, and context management.
"""

import os
import sys

# Add the project root directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from playwright.async_api import async_playwright


class BrowserManager:
    """
    Manages browser instances and contexts for HeyGen automation.
    """
    
    def __init__(self, user_data_dir="./user_data"):
        """
        Initialize BrowserManager.
        
        Args:
            user_data_dir (str): Directory to store browser user data
        """
        self.user_data_dir = user_data_dir
        self.playwright = None
        self.context = None
        self.page = None
    
    async def start_browser(self, headless=False):
        """
        Start browser with persistent context.
        
        Args:
            headless (bool): Whether to run browser in headless mode
            
        Returns:
            tuple: (context, page) Browser context and page instances
        """
        self.playwright = await async_playwright().start()
        
        # Launch browser with persistent context to maintain session
        self.context = await self.playwright.chromium.launch_persistent_context(
            user_data_dir=self.user_data_dir,
            channel="chrome",
            headless=headless,
            args=[
                "--no-sandbox",
                "--disable-dev-shm-usage",
                "--disable-extensions",
                "--disable-gpu"
            ]
        )
        
        # Get or create page
        self.page = self.context.pages[0] if self.context.pages else await self.context.new_page()
        
        # Set browser language
        await self.page.set_extra_http_headers({"Accept-Language": "en-US,en;q=0.9"})
        
        return self.context, self.page
    
    async def navigate_to_heygen(self):
        """
        Navigate to HeyGen website.
        
        Returns:
            Page: The page instance after navigation
        """
        await self.page.goto("https://app.heygen.com/")
        return self.page
    
    async def close_browser(self):
        """
        Close browser and cleanup resources.
        """
        if self.context:
            await self.context.close()
        if self.playwright:
            await self.playwright.stop()